package com.wx.util;

import java.util.HashMap;
import java.util.Map;

import com.wx.common.WxConfig;
import com.wx.exception.WxException;

import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;

public class WxMpUtil {
	private static Map<String, WxMpConfigStorage> storageMap = new HashMap<String, WxMpConfigStorage>();
	private static WxMpService wxMpService;

	public static WxMpConfigStorage getStoregeByAppName(String appName) throws WxException {
		if (!storageMap.containsKey(appName)) {
			WxConfig wxConfig = WxConfig.dao.findFirst("select * from tbl_wxconfig where appName =?", appName);
			if (wxConfig == null) {
				// 抛出异常
				throw new WxException(String.format("微信配置%s，不存在", appName));
			} else {
				WxMpConfigStorage storage = new WxMpConfigStorageSimple(wxConfig);
				storageMap.put(appName, storage);
			}
		}
		return storageMap.get(appName);
	}

	public static WxMpService getWxMpServiceByAppName(String appName) throws WxException {
		if (appName == null) {
			//TODO
			//throw new WxException("appName 为null");
			return getTestService();
		}
		
		
		if (wxMpService == null) {
			wxMpService = new WxMpServiceImpl();
		}
		wxMpService.setWxMpConfigStorage(getStoregeByAppName(appName));
		return wxMpService;
	}

	public static WxMpService getTestService() {
		if (wxMpService == null) {
			wxMpService = new WxMpServiceImpl();
		}
		wxMpService.setWxMpConfigStorage(new WxMpConfigStorageSimple(false));
		return wxMpService;
	}

}
